package com.acegear.horizon.domain.events.handlers;

import com.acegear.horizon.domain.events.AGDailyCreateEvent;
import com.acegear.horizon.domain.events.AGDailyDeleteEvent;
import com.acegear.horizon.domain.events.AGDailyModifiedEvent;
import com.acegear.horizon.domain.events.ActivityCreateEvent;
import com.acegear.horizon.domain.events.EventSource;
import com.acegear.horizon.domain.models.jpa.AGDaily;
import com.acegear.horizon.domain.repository.jpa.AGDailyRepository;
import com.acegear.horizon.vendor.ons.ONSConsumer;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.PostConstruct;


import java.util.Optional;

/**
 * Created by guoweike on 17/2/25.
 */
@Component
public class AGDailyEventHandler {

    @Autowired
    private AGDailyRepository agDailyRepository;

    @Autowired
    private ONSConsumer consumer;

    @PostConstruct
    public void aGDailyCreateONS() {
        consumer.consume(AGDailyCreateEvent.class, this::aGDailyCreate);
    }

    @PostConstruct
    public void aGDailyModifiedONS() {
        consumer.consume(AGDailyModifiedEvent.class, this::aGDailyModified);
    }

    @PostConstruct
    public void aGDailyDeleteONS() {
        consumer.consume(AGDailyDeleteEvent.class, this::aGDailyDelete);
    }

    public void aGDailyCreate(AGDailyCreateEvent agDailyCreateEvent) {

        AGDaily agDaily = new AGDaily(
                agDailyCreateEvent.getDailyId(),
                agDailyCreateEvent.getDate(),
                agDailyCreateEvent.isState(),
                agDailyCreateEvent.getBackground(),
                agDailyCreateEvent.getAgDailyItemArrayList());
        agDailyRepository.save(agDaily);
    }

    @Transactional
    public void aGDailyModified(AGDailyModifiedEvent agDailyModifiedEvent) {
        Optional<AGDaily> agDailyOptional = agDailyRepository.findTopByDailyId(agDailyModifiedEvent.getDailyId());
        if (agDailyOptional.isPresent()) {
            AGDaily agDaily1 = agDailyOptional.get();
            agDaily1.setBackground(agDailyModifiedEvent.getBackground());
            agDaily1.setPushed(agDailyModifiedEvent.isState());
            agDaily1.setDate(agDailyModifiedEvent.getDate());
            agDaily1.setFeeds(agDailyModifiedEvent.getAgDailyItemArrayList());
            agDailyRepository.save(agDaily1);
        }
    }

    @Transactional
    public void aGDailyDelete(AGDailyDeleteEvent agDailyDeleteEvent) {
        Optional<AGDaily> agDailyOptional = agDailyRepository.findTopByDailyId(agDailyDeleteEvent.getaGId());
        agDailyOptional.ifPresent(agDailyRepository::delete);
    }
}
